package com.group5.onlinegame.handler;

import com.group5.onlinegame.entity.LoginUser;
import com.group5.onlinegame.entity.Modules;
import com.group5.onlinegame.service.ILoginService;
import com.group5.onlinegame.service.IPowerService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("/")
public class LoginHandler {

    @Resource
    private IPowerService powerService;
    @Resource
    private ILoginService loginService;

    @RequestMapping("login")
    public String login(String username, String password,HttpSession session) {
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username, password);
        try {
            subject.login(usernamePasswordToken);
        } catch (Exception e) {
            System.out.println("用户名或密码错误!请重新登录");
            return "redirect:/login.jsp";
        }
        LoginUser loginUser = loginService.getLoginUser(new LoginUser(username,password));
        session.setAttribute("loginUser",loginUser);
        List<Modules> modulesmain = powerService.getmainmodule(username);
        List<Modules> modulesson = powerService.getsonmodule();
        session.setAttribute("modulesmain",modulesmain);
        session.setAttribute("modulesson",modulesson);
        return "main";
    }

    @RequestMapping("logout")
    public String logout(){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "redirect:/login.jsp";
    }

}
